<template>
	<div id="mainMap">
		<toolBar></toolBar>
		<ruler></ruler>

		<bassmapToggle :basemap="basemap"></bassmapToggle>
		<div class="mainShowCoords">
			<span class="left">纬度:{{ pingmuCoords.lat }}</span>
			<span class="center">经度:{{ pingmuCoords.lon }}</span>
			<span class="right">比例尺:1:{{ pingmuCoords.zoom }}</span>
		</div>
		<div class="copyright">
			<span class="left">技术支持单位：自然资源部第一地理信息制图院</span>
		</div>
		<div id="legendContainer" v-show="isLegendShow"></div>
		<XzqMsg v-show="isShowXzq"></XzqMsg>
		<analyst-tool-panel :showDrawer="isShowAnalystTool" />
		<Spin size="large" fix v-if="spinShow">
			<Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
			<div>Loading</div>
		</Spin>
		<chartRightBottom></chartRightBottom>
		<chartRightTop></chartRightTop>
	</div>
</template>
<script>
import config from "../../config.js";
import { mapState } from "vuex";
import toolBar from "./ToolBar";
import ruler from "./Ruler";
import analystToolPanel from "./AnalystToolPanel";
import bassmapToggle from "./BaseToggle";
import XzqMsg from "./XzqMsg";
import chartRightBottom from "./chartRightBottom"
import chartRightTop from "./chartRightTop"

import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import TileInfo from "@arcgis/core/layers/support/TileInfo";
import Basemap from "@arcgis/core/Basemap";
// import Legend from "@arcgis/core/widgets/Legend";

// import Home from "@arcgis/core/widgets/Home";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
import TileLayer from "@arcgis/core/layers/TileLayer";
import ImageryLayer from "@arcgis/core/layers/ImageryLayer";
import Polygon from "@arcgis/core/geometry/Polygon";
import QueryTask from "@arcgis/core/tasks/QueryTask";

import Query from "@arcgis/core/rest/support/Query";
import Extent from "@arcgis/core/geometry/Extent";
export default {
	name: "mainMap",
	data() {
		return {
			pingmuCoords: {
				lat: 87.234,
				lon: 31.787,
				zoom: 144448,
			},
			basemap: null,
			layerState: [],
			MapImageLayer: null,
			map: null,
			FeatureLayer: null,
			TileLayer: null,
			ImageryLayer: null,
			Polygon: null,
			view: null,
			spinShow: true,
		};
	},
	watch: {
		layers: {
			handler() {
				let that = this;
				console.log(that.spinShow);
				let addRemove = that.changeLayerState();
				if (addRemove[1]) {
					that.removeLayer(addRemove[1]);
					if (addRemove[1].isShowPopup) {
						let temp = that.showPopupId.indexOf(addRemove[1].id);
						if (temp !== -1) {
							that.showPopupId.splice(temp, 1);
						}
					}
				}
				if (addRemove[0]) {
					that.chooseLayerType_add(addRemove[0], true);
					if (addRemove[0].isShowPopup) {
						that.showPopupId.push(addRemove[0].id);
					}
				}
				that.spinShow = false;
			},
			deep: true,
		},
	},
	computed: {
		...mapState({
			isLegendShow: (state) => state.oneMap.isLegendShow,
			layers: (state) => state.oneMap.layers,
			startLayers: (state) => state.oneMap.initLayers,
			userServices: (state) => state.oneMap.userServices,
			isShowXzq: (state) => state.oneMap.isShowXzq,
			isShowAnalystTool: (state) => state.oneMap.isShowAnalystTool,
		}),
	},
	components: {
		toolBar,
		ruler,
		bassmapToggle,
		XzqMsg,
		analystToolPanel,
		chartRightBottom,
		chartRightTop
	},
	mounted() {
		this.initMap();
		var layer = new TileLayer({
			url: "http://59.218.251.20:31993/arcgis/rest/services/ShanxiVectorLayer2021/MapServer",
		});
		let tileInfo = {
			rows: 256,
			cols: 256,
			dpi: 96,
			format: "Mixed",
			compressionQuality: 75,
			origin: { x: -180, y: 90 },
			spatialReference: { wkid: 4490, latestWkid: 4490 },
			lods: [
				{ level: 0, resolution: 0.703125, scale: 2.95829355454566e8 },
				{ level: 1, resolution: 0.3515625, scale: 1.47914677727283e8 },
				{ level: 2, resolution: 0.17578125, scale: 7.39573388636414e7 },
				{ level: 3, resolution: 0.087890625, scale: 3.69786694318207e7 },
				{ level: 4, resolution: 0.0439453125, scale: 1.84893347159103e7 },
				{ level: 5, resolution: 0.02197265625, scale: 9244667.35795517 },
				{ level: 6, resolution: 0.010986328125, scale: 4622333.67897759 },
				{ level: 7, resolution: 0.0054931640625, scale: 2311166.83948879 },
				{ level: 8, resolution: 0.00274658203125, scale: 1155583.4197444 },
				{ level: 9, resolution: 0.001373291015625, scale: 577791.709872198 },
				{ level: 10, resolution: 6.866455078125e-4, scale: 288895.854936099 },
				{ level: 11, resolution: 3.4332275390625e-4, scale: 144447.92746805 },
				{
					level: 12,
					resolution: 1.71661376953125e-4,
					scale: 72223.9637340248,
				},
				{
					level: 13,
					resolution: 8.58306884765625e-5,
					scale: 36111.9818670124,
				},
				{
					level: 14,
					resolution: 4.291534423828125e-5,
					scale: 18055.9909335062,
				},
				{
					level: 15,
					resolution: 2.1457672119140625e-5,
					scale: 9027.9954667531,
				},
				{
					level: 16,
					resolution: 1.0728836059570312e-5,
					scale: 4513.99773337655,
				},
				{
					level: 17,
					resolution: 5.364418029785156e-6,
					scale: 2256.99886668828,
				},
				{
					level: 18,
					resolution: 2.682209014892578e-6,
					scale: 1128.49943334414,
				},
				{
					level: 19,
					resolution: 1.341104507446289e-6,
					scale: 564.249716672069,
				},
			],
		};
		layer.tileInfo = TileInfo.fromJSON(tileInfo);
		this.map.add(layer);

		// 轨迹要素图层添加
		this.map.add(this.$commonLayers.trailLayer);
		this.map.add(this.$commonLayers.trailPointLayer);
		this.map.add(this.$commonLayers.trailPointHotLayer);
	},
	methods: {
		//设置弹窗配置
		getPopupTemplate(item) {
			let content = [];
			for (let i = 0; i < item.templateConfig.length; i++) {
				let template = {
					fieldName: item.templateConfig[i].fieldName,
					label: item.templateConfig[i].labelName,
				};
				content.push(template);
			}
			return {
				title: item.popupTitle,
				content: [
					{
						type: "fields",
						fieldInfos: content,
					},
				],
			};
		},
		getDymanicSubLayer(input, item) {
			let sublayers = [];
			input.forEach((resLayer) => {
				let tempSublayer = {};
				tempSublayer["id"] = resLayer.id;
				if (item.popupConfig) {
					for (let q = 0; q < item.popupConfig.length; q++) {
						if (item.popupConfig[q].index == resLayer.id) {
							tempSublayer["popupEnabled"] = item.popupConfig[q].isShowPopup;
							tempSublayer["popupTemplate"] = this.getPopupTemplate(
								item.popupConfig[q]
							);
						}
					}
				}

				sublayers.push(tempSublayer);
			});
			return sublayers;
		},
		movetoPosition(isGoto, i, layer, tempMsg) {
			if (isGoto || i == tempMsg.length - 1) {
				if (layer.spatialReference.wkid == this.view.spatialReference.wkid) {
					this.view.goTo(function () {
						this.view.extent = layer.fullExtent;
					});
				} else {
					this.gotoCoor(this.view, layer);
				}
			}
		},
		chooseLayerType_add(inputItem, isGoto) {
			if (JSON.stringify(inputItem) == "{}") {
				return;
			}
			let tempMsg = [].concat(inputItem) || [].push(inputItem);
			let that = this;
			for (let i = 0; i < tempMsg.length; i++) {
				let item = tempMsg[i];
				this.$.ajax({
					type: "get",
					url: item.url + "?f=json",
					dataType: "text",
					success: function (res) {
						let layerContent = JSON.parse(res).layers;
						if (res.indexOf('"supportsDynamicLayers":true') !== -1) {
							let layer = new that.MapImageLayer({
								url: item.url,
								id: item.id,
								title: item.title,
								sublayers: that.getDymanicSubLayer(layerContent, item),
							});
							that.map.add(layer);
							layer.when(function () {
								that.movetoPosition(isGoto, i, layer, tempMsg);
							});
						} else if (res.indexOf("tileInfo") !== -1) {
							let layer = new that.TileLayer({
								url: item.url,
								id: item.id,
								title: item.title,
								sublayers: that.getDymanicSubLayer(layerContent, item),
							});
							that.map.add(layer);
							if (isGoto || i == tempMsg.length - 1) {
								layer.when(function () {
									that.movetoPosition(isGoto, i, layer, tempMsg);
								});
							}
						} else if (res.indexOf("Raster") !== -1) {
							let layer = new that.ImageryLayer({
								url: item.url,
								id: item.id,
								title: item.title,
							});
							that.map.add(layer);
							if (isGoto || i == tempMsg.length - 1) {
								layer.when(function () {
									that.movetoPosition(isGoto, i, layer, tempMsg);
								});
							}
						} else if (
							res.indexOf("supportsPagination") !== -1 ||
							item.url.indexOf("FeatureServer") !== -1
						) {
							let layer = new that.FeatureLayer({
								url: item.url,
								id: item.id,
								title: item.title,
								outFields: ["*"],
							});
							console.log(layer);
							that.map.add(layer);
							if (isGoto || i == tempMsg.length - 1) {
								layer.when(function () {
									that.movetoPosition(isGoto, i, layer, tempMsg);
								});
							}
						} else {
							alert("图层不支持");
						}
					},
					error: (err) => {
						// console.log("error");
						// console.log(err);
					},
				});
			}
		},
		gotoCoor(view, layer) {
			let that = this;
			let gotoUrl =
				"https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer/project";
			let inSar = layer.spatialReference.wkid;
			let inLatestWkid = layer.spatialReference.latestWkid;
			let outSar = view.spatialReference.wkid;
			let xmin = layer.fullExtent.xmin;
			let xmax = layer.fullExtent.xmax;
			let ymin = layer.fullExtent.ymin;
			let ymax = layer.fullExtent.ymax;
			let geometryData = {
				f: "json",
				outSR: outSar,
				inSR: inSar,
				geometries: JSON.stringify({
					geometryType: "esriGeometryPolygon",
					geometries: [
						{
							rings: [
								[
									[xmin, ymin],
									[xmin, ymax],
									[xmax, ymax],
									[xmax, ymin],
									[xmin, ymin],
								],
							],
							spatialReference: {
								wkid: inSar,
								latestWkid: inLatestWkid,
							},
						},
					],
				}),
			};
			this.$.get(gotoUrl, geometryData).done((res) => {
				let polygon = new that.Polygon({
					rings: res.geometries[0].rings,
					spatialReference: {
						wkid: outSar,
					},
				});
				view.goTo(polygon);
			});
		},
		removeLayer(input) {
			for (let k in input) {
				if (k == "id") {
					let foundLayer = this.map.allLayers.find(function (layer) {
						return layer.id == input[k];
					});
					this.map.remove(foundLayer);
				}
			}
		},
		changeLayerState() {
			let add = {};
			let remove = {};
			let result = [];
			if (this.layers) {
				if (this.layers.selected == true) {
					add["id"] = this.layers.id;
					add["url"] = this.layers.url;
					add["title"] = this.layers.title;
					add["isShowPopup"] = this.layers.isShowPopup;
					add["popupConfig"] = this.layers.popupConfig;
					this.layerState.push(this.layers.id);
				}
				if (this.layers.selected == false) {
					let index = -1;
					for (let i = 0; i < this.layerState.length; i++) {
						if (
							this.layerState[i] == this.layers.id &&
							this.layers.selected == false
						) {
							index = i;
							break;
						}
					}
					remove["id"] = this.layers.id;
					remove["url"] = this.layers.url;
					remove["isShowPopup"] = this.layers.isShowPopup;
					this.layerState.splice(index, 1);
				}
				result.push(add);
				result.push(remove);
			}

			return result;
		},
		initMap() {
			let that = this;
			that.MapImageLayer = MapImageLayer;
			that.FeatureLayer = FeatureLayer;
			that.ImageryLayer = ImageryLayer;
			that.TileLayer = TileLayer;
			that.Polygon = Polygon;
			that.basemap = initBasemap();

			// let layer_vec = new WebTileLayer({
			// 	urlTemplate:
			// 		"http://59.218.251.20:31993/arcgis/rest/services/ShanxiVector2021/MapServer",
			// 	// tileInfo: tileInfo,
			// 	id: "layer_vec",
			// 	//visible:false
			// });

			// console.log(layer_vec);
			that.map = new Map({
				// basemap: that.basemap.tdtyxBasemap,
				// spatialReference: {
				// 	wkid: 4490,
				// },
				// basemap: {
				// 	baseLayers: [layer_vec]
				// }
			});

			// 初始地图中心点： 尼玛县政府的经纬度
			const view = new MapView({
				container: "mainMap",
				// spatialReference: {
				// 	wkid: 4490
				// 	// wkid: 4326,
				// },
				map: that.map,
				center: [109.041, 34.268],
				zoom: 6,
			});
			view.extent = new Extent({
				xmin: 108.17440830780113,
				ymin: 33.92757864226665,
				xmax: 109.49139702576294,
				ymax: 34.51466172561251,
				spatialReference: {
				wkid: 4490,
				},
			});
			view.ui.components = [""];
			//view.popup.autoOpenEnabled = false;
			that.view = view;

			if (that.startLayers) {
				that.startLayers.forEach((item) => {
					that.layerState.push(item.id);
				});

				that.chooseLayerType_add(that.startLayers, false);
			}

			// initWidgets(view);

			view.when(function () {
				view.on("pointer-move", function (e) {
					let point = view.toMap({ x: e.x, y: e.y });
					that.pingmuCoords.lat = point.latitude.toFixed(3);
					that.pingmuCoords.lon = point.longitude.toFixed(3);
				});
				view.on("mouse-wheel", function (e) {
					that.pingmuCoords.zoom = view.scale.toFixed(0);
				});

				view.on("click", function (e) {
					view.hitTest(e).then((response) => {
						if (response.results.length > 0) {
							let queryTaskUrl =
								response.results[0].graphic.layer.url +
								"/" +
								response.results[0].graphic.layer.layerId;
							let targetLayer;

							for (let z = 0; z < that.userServices.length; z++) {
								if (
									that.userServices[z].id ==
									response.results[0].graphic.layer.id
								) {
									targetLayer = that.userServices[z];
									break;
								}
							}
							let queryTask = new QueryTask(queryTaskUrl);
							let params = new Query();
							params.outFields = ["*"];

							executeQueryTask(
								e,
								queryTask,
								params,
								targetLayer.popupConfig[
									response.results[0].graphic.layer.layerId
								]
							);
						}
					});
				});
			});

			that.$store.dispatch("oneMap/updateMaps", {
				map: that.map,
				view: view,
			});

			that.spinShow = false;
			console.log("初始化组件");
			function executeQueryTask(event, queryTask, params, targetLayer) {
				params.geometry = event.mapPoint;
				queryTask
					.execute(params)
					.then(function (response) {
						var results = response.features;
						let content = [];
						targetLayer.templateConfig.forEach((template) => {
							let temp = {
								fieldName: template.fieldName,
								label: template.labelName,
							};
							content.push(temp);
						});
						return results.map(function (result) {
							if (targetLayer.isShowPopup) {
								result.popupTemplate = {
									title: targetLayer.popupTitle,
									content: [
										{
											type: "fields",
											fieldInfos: content,
										},
									],
								};
							}
							return result;
						});
					})
					.then(showPopup);

				function showPopup(response) {
					if (response.length > 0) {
						if (view.popup.autoOpenEnabled) {
							view.popup.open({
								features: response,
								location: event.mapPoint,
							});
						}
					}
					document.getElementById("viewDiv").style.cursor = "auto";
				}
			}
			function initBasemap() {
				const tdtSubDomain = ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"];
				const tdtLyr = new WebTileLayer({
					urlTemplate: tdtUrlRenderer("vec_w"),
					subDomains: tdtSubDomain,
				});
				const tdtbzLyr = new WebTileLayer({
					urlTemplate: tdtUrlRenderer("cva_w"),
					subDomains: tdtSubDomain,
				});
				const tdtBasemap = new Basemap({
					id: "tdt",
					title: "天地图",
					baseLayers: [tdtLyr, tdtbzLyr],
				});
				const tdtyxLyr = new WebTileLayer({
					urlTemplate: tdtUrlRenderer("img_w"),
					subDomains: tdtSubDomain,
				});
				const tdtyxbzLyr = new WebTileLayer({
					urlTemplate: tdtUrlRenderer("cia_w"),
					subDomains: tdtSubDomain,
				});
				const tdtyxBasemap = new Basemap({
					id: "tdtyx",
					title: "天地图影像",
					baseLayers: [tdtyxLyr, tdtyxbzLyr],
				});
				return {
					tdtBasemap,
					tdtyxBasemap,
				};
			}
			function tdtUrlRenderer(type) {
				return (
					"https://{subDomain}.tianditu.gov.cn/DataServer?T=" +
					type +
					"&x={col}&y={row}&l={level}&tk=" +
					config.tdtConfig.token
				);
			}
			function initWidgets(view) {
				const homeWidget = new Home({
					view: view,
				});
				// view.ui.add(homeWidget, "top-left");
				const legendWidget = new Legend({
					view: view,
					container: document.getElementById("legendContainer"),
				});
				view.ui.add(legendWidget);
			}
		},
	},
};
</script>
<style scoped>
#mainMap {
	width: 100%;
	height: 100%;
	position: relative;
}
.mainShowCoords {
	width: 16%;
	height: 30px;
	background: rgba(0, 63, 84);
	position: fixed;
	bottom: 15px;
	/* left: 451px; */
	left: 380px;
	border-radius: 4px;
	display: flex;
	justify-content: space-around;
}
.copyright{
	width: 16%;
	height: 30px;
	background: rgba(0, 63, 84);
	position: fixed;
	bottom: 15px;
	left: 30px;
	border-radius: 4px;
	display: flex;
	justify-content: space-around;
}
.left,
.center,
.right {
	display: inline-block;
	line-height: 30px;
	font-size: 13px;
	font-family: PingFangSC-Medium, PingFang SC;
	font-weight: 500;
	color: rgba(255, 255, 255, 0.9);
	text-shadow: 0px 2px 4px rgba(0, 0, 0, 0.5);
}

#legendContainer {
	position: fixed;
	bottom: 80px;
	right: 200px;
	width: 325px;
	overflow-y: auto;
	max-height: 500px;
}
</style>
